package handler

import (
	"api/basic/config"
	"api/common"
	"api/internal/request"
	"api/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
	pb "user_server/proto"
)

func UserLogin(c *gin.Context) {
	json := request.UserLoginRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		common.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	con, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		common.JsonRes(c, 400, "grpc连接失败", nil)
		return
	}
	req := &pb.UserLoginReq{
		Username: json.Username,
		Password: json.Password,
	}
	client := pb.NewUserClient(con)
	id, err := client.UserLogin(c, req)
	if err != nil {
		return
	}
	claims := pkg.CustomClaims{
		ID:             uint(id.Id),
		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Unix() + int64(config.DataConfig.Jwt.Seconds)},
	}
	newJWT := pkg.NewJWT(config.DataConfig.Jwt.Key)
	token, _ := newJWT.CreateToken(claims)
	common.JsonRes(c, 200, "登录成功", token)
}
